package com.cherrypt.api.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cherrypt.api.common.enums.ResultEnum;
import com.cherrypt.api.common.exception.TipException;
import com.cherrypt.api.core.dao.ConfigDao;
import com.cherrypt.api.model.dataobject.Config;
import com.cherrypt.api.core.service.ConfigService;
import com.cherrypt.api.core.util.CherryUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigDao, Config> implements ConfigService {
    private static final Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    @Value("${api.config.redis.config.value}")
    private String configValue;

    @Value("${api.config.redis.config.exp}")
    private long configExp;

    @Override
    public void saveRedisConfig(Config config) {
        valueOperations.set(configValue, config, Duration.ofSeconds(configExp));
    }

    @Override
    public Config getConfig() throws TipException {
        Config config = getRedisConfig();
        if (config == null) {
            config = this.list().get(0);
            if (config == null) {
                throw new TipException(ResultEnum.CONFIG_ERROR);
            }
            CherryUtils.config = config;
            saveRedisConfig(config);
            logger.info("缓存Config到Redis");
        }
        return config;
    }

    @Override
    public Config getRedisConfig() {
        return (Config) valueOperations.get(configValue);
    }

    @Override
    public boolean removeRedisConfig() {
        return redisTemplate.delete(configValue);
    }
}
